<template>
    <div id="new-student">
        <el-breadcrumb separator="/" class="common-bread">
            <el-breadcrumb-item :to="{ path: '/student' }">学生管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{operationText}}学生</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="form mt10 contentBox">
            <div class="list_head">
                <span class="head_name">学生信息</span>
                <el-button type="primary" @click="$router.push('/student')" class="fr ml10">取消</el-button>
                <el-button type="primary" @click="save" class="fr">保存</el-button>
            </div>
            <el-form label-width="140px" :model="form" :rules="rules" ref="form">
                <el-form-item label="学校：" prop="schoolName">
                    <el-autocomplete v-model="form.schoolName" :fetch-suggestions="querySearch" placeholder="请输入使用学校"
                        @select="handleSelect" clearable></el-autocomplete>
                </el-form-item>
                <el-form-item label="学生名称：" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="性别：" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="民族：" prop="nation">
                    <el-input v-model="form.nation"></el-input>
                </el-form-item>
                <el-form-item label="出生日期：" prop="birthday">
                    <el-date-picker v-model="form.birthday" type="date" placeholder="yyyy/MM/dd" format="yyyy/MM/dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="编号：" prop="number">
                    <el-input v-model="form.number"></el-input>
                </el-form-item>
                <el-form-item label="学籍号：" prop="studentNumber">
                    <el-input v-model="form.studentNumber"></el-input>
                </el-form-item>
                <el-form-item label="入学年份：" prop="enrollmentYear">
                    <el-select v-model="form.enrollmentYear">
                        <el-option :label='item.label' :value='item.value' v-for="item in enterYears" :key="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年级：" prop="gradeId" ref="grade">
                    <el-select v-model="form.gradeId" @change="getClasses()">
                        <el-option :label='item.gradeName' :value='item.gradeId' v-for="item in grades"
                            :key="item.gradeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级：" prop="classId" ref="class">
                    <el-select v-model="form.classId">
                        <el-option :label='item.name' :value='item.classId' v-for="(item,index) in classes"
                            :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学生状态：" prop="status" v-if="id">
                    <el-select v-model="form.status">
                        <el-option label='在校' value='0'></el-option>
                        <el-option label='已毕业' value='1'></el-option>
                        <el-option label='已转校' value='2'></el-option>
                        <el-option label='已开除' value='3'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="家庭住址：" prop="address">
                    <el-input type="textarea" v-model="form.address" class="my-textarea" :autosize="{minRows: 4}">
                    </el-input>
                </el-form-item>

                <template v-if="!id">
                    <div class="list_head">
                        <span class="head_name">家长信息</span>
                    </div>
                    <el-form-item label="成员1姓名：" prop="member1Name">
                        <el-input v-model="form.member1Name"></el-input>
                    </el-form-item>
                    <el-form-item label="成员1关系：" prop="member1Relation" required>
                        <el-select v-model="form.member1Relation">
                            <el-option :label='item.label' :value='item.value' v-for="item in options"
                                :key="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="成员1联系电话：" prop="member1Phonoe">
                        <el-input v-model="form.member1Phonoe"></el-input>
                    </el-form-item>
                    <el-form-item label="成员2姓名：" prop="member2Name">
                        <el-input v-model="form.member2Name"></el-input>
                    </el-form-item>
                    <el-form-item label="成员2关系：" prop="member2Relation">
                        <el-select v-model="form.member2Relation">
                            <el-option :label='item.label' :value='item.value' v-for="item in options"
                                :key="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="成员2联系电话：" prop="member2Phonoe">
                        <el-input v-model="form.member2Phonoe"></el-input>
                    </el-form-item>
                </template>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";
    export default {
        data() {
            let validBlank = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    callback();
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validCode = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (value.length > 19 || value.length < 16) {
                        callback(new Error("学籍号长度应为16-19个字符"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validNumber = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (value.length > 50) {
                        callback(new Error("字符长度不应超过50个字符"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            let validPhone = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (!/^1[3456789]\d{9}$/.test(value)) {
                        callback("请输入格式正确的联系电话");
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            return {
                id: "",
                operationText: "添加",
                schoolId: "",
                schools: [],
                enterYears: this.getEnterYears(),
                grades: this.$util.getGrades(),
                classes: [],
                options: [
                    { label: "父亲", value: "1", gender: 1 },
                    { label: "母亲", value: "2", gender: 0 },
                    { label: "爷爷", value: "3", gender: 1 },
                    { label: "奶奶", value: "4", gender: 0 },
                    { label: "外公", value: "5", gender: 1 },
                    { label: "外婆", value: "6", gender: 0 },
                    { label: "其他监护人", value: "7", gender: 1 }
                ],
                studentStatusId: "",
                parents: [],
                form: {
                    schoolName: "",
                    name: "",
                    gender: "1",
                    birthday: "",
                    studentNumber: "",
                    number: "",
                    nation: "",
                    status: "0",
                    enrollmentYear: '',
                    gradeId: "",
                    classId: "",
                    address: "",
                    member1Name: "",
                    member1Relation: "1",
                    member1Phonoe: "",
                    member2Name: "",
                    member2Relation: "2",
                    member2Phonoe: ""
                },
                rules: {
                    schoolName: [
                        { required: true, message: "学校名称不能为空", trigger: "change" }
                    ],
                    name: [
                        { required: true, message: "学生名称不能为空", trigger: "blur" },
                        { validator: validBlank }
                    ],
                    gender: [
                        { required: true }
                    ],
                    status: [
                        { required: true }
                    ],
                    nation: [
                        { required: true, message: "民族不能为空", trigger: "blur" },
                        { validator: validBlank }
                    ],
                    birthday: [
                        { type: "date", required: true, message: "请选择出生日期", trigger: "blur" }
                    ],
                    studentNumber: [
                        { required: true, message: "学籍号不能为空", trigger: "blur" },
                        { validator: validCode }
                    ],
                    number: [
                        { required: true, message: "编号不能为空", trigger: "blur" },
                        { validator: validNumber }
                    ],
                    enrollmentYear: [
                        { required: true, message: "请选择入学年份", trigger: "change" }
                    ],
                    gradeId: [
                        { required: true, message: "请选择年级", trigger: "change" }
                    ],
                    classId: [
                        { required: true, message: "请选择班级", trigger: "change" }
                    ],
                    member1Name: [
                        { required: true, message: "家长姓名不能为空", trigger: "blur" },
                        { validator: validBlank }
                    ],
                    member1Phonoe: [
                        { required: true, message: "联系电话不能为空", trigger: "change" },
                        { validator: validPhone, trigger: "blur" }
                    ]
                }
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.getSchools();
            this.$util.setStore("stuSelect", "1");

            this.id = this.$util.getUrlParam("id");
            if (this.id) {
                this.operationText = "编辑";
                this.getDetail();
            }
        },
        methods: {
            //获取学校列表
            getSchools() {
                this.$util.getSchools().then(schools => {
                    schools.forEach(item => {
                        this.schools.push({
                            value: item.name,
                            schoolId: item.schoolId,
                            haveHigh: item.haveHigh,
                            haveMiddle: item.haveMiddle,
                            havePrimary: item.havePrimary
                        })
                    });
                });
            },
            //获取班级列表
            getClasses(id) {
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: {
                        grade: this.form.gradeId,
                        schoolId: this.schoolId,
                        pageSize: 100,
                        pageNum: 1
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.classes = [];
                        this.$refs.class.resetField();
                        if (!response.data.data) return;
                        let list = response.data.data.content;

                        list.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            item.name = item.name ? className + `（${item.name}）` : className;

                            this.classes.push({
                                name: item.name,
                                classId: item.classId
                            })
                        })

                        if (id) this.form.classId = id;
                    }
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;

                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.$refs.grade.resetField();
                this.$refs.class.resetField();
                this.grades = this.$util.getGrades(schoolType);
            },
            //返回入学年份
            getEnterYears() {
                let years = [], currentYear = new Date().getFullYear();
                for (let i = 0; i < 7; i++) {
                    years.push({
                        label: (currentYear - i) + "年",
                        value: (currentYear - i)
                    })
                }
                return years;
            },
            //返回关系
            getRelation(value) {
                let relationName;
                this.options.forEach(item => {
                    if (item.value == value) relationName = item.label;
                })

                return relationName;
            },
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {

                        let requestParam = {
                            name: this.form.name.trim(),
                            schoolId: this.schoolId,
                            schoolName: this.form.schoolName,
                            gender: this.form.gender * 1,
                            nation: this.form.nation.trim(),
                            birthday: new Date(this.form.birthday).getTime(),
                            studentNumber: this.form.studentNumber.trim(),
                            number: this.form.number.trim(),
                            enrollmentYear: new Date(this.form.enrollmentYear + "/09/01 00:00").getTime(),
                            grade: this.form.gradeId,
                            classId: this.form.classId,
                            status: this.form.status,
                            address: this.form.address ? this.form.address.trim() : ""
                        }

                        if (!this.id) {
                            //家庭成员
                            let studentParentModels = [{
                                name: this.form.member1Name,
                                phone: this.form.member1Phonoe,
                                relationName: this.getRelation(this.form.member1Relation)
                            }]

                            if (this.form.member2Name && this.form.member2Phonoe) {
                                studentParentModels.push({
                                    name: this.form.member2Name,
                                    phone: this.form.member2Phonoe,
                                    relationName: this.getRelation(this.form.member2Relation)
                                })

                            }

                            requestParam.studentParentModels = studentParentModels;
                        }

                        if (this.id) {
                            requestParam.studentId = this.id;
                            requestParam.studentStatusId = this.studentStatusId;
                            this.parents.forEach(item => {
                                for (let key in item) {
                                    if (!item[key]) delete item[key];
                                }
                            })
                            requestParam.studentParentModels = [...this.parents];
                        };

                        this.$axios.post("/adminapi/v1/user/student/addOrEdit", requestParam).then(response => {
                            if (response.data.error == 10000) {
                                this.$router.push("/student");
                                this.$util.successMsg("保存成功");
                            } else {
                                this.$util.errorMsg(response.data.message);
                            }
                        })
                    } else {
                        this.$util.errorMsg("请正确填写表单信息");
                    }
                })
            },
            //获取家长类型
            getParentsType(relationName) {
                let type;
                this.options.forEach(item => {
                    if (item.label == relationName) type = item.value;
                })
                if (!type) type = "7";
                return type;
            },
            //获取学生详情
            getDetail() {
                this.$axios.post("/adminapi/v1/user/student/info?studentId=" + this.id).then(response => {
                    if (response.data.error == 10000) {
                        let info = response.data.data;
                        this.schoolId = info.schoolId;
                        this.studentStatusId = info.studentStatusId;
                        let parents = info.studentParentModels;
                        this.parents = parents;
                        this.form = {
                            name: info.name,
                            schoolName: info.schoolName,
                            gender: info.gender + "",
                            nation: info.nation,
                            birthday: new Date(info.birthday * 1),
                            studentNumber: info.studentNumber,
                            number: info.number,
                            enrollmentYear: info.enrollmentYear ? new Date(info.enrollmentYear * 1).format("yyyy") * 1 : "",
                            gradeId: info.grade,
                            classId: "",
                            address: info.address,
                            status: info.status + "",
                            member1Name: parents[0] ? parents[0].name : "",
                            member1Relation: parents[0] ? this.getParentsType(parents[0].relationName) : "1",
                            member1Phonoe: parents[0] ? parents[0].phone : "",
                            member2Name: parents[1] ? parents[1].name : "",
                            member2Relation: parents[1] ? this.getParentsType(parents[1].relationName) : "2",
                            member2Phonoe: parents[1] ? parents[1].phone : ""
                        };

                        this.getClasses(info.classId);
                    }
                })
            }
        }
    }
</script>
<style>
    #new-student .my-textarea {
        width: 500px;
    }

    #new-student .el-select {
        width: 300px;
    }

    #new-student .el-date-editor.el-input,
    #new-student .el-date-editor.el-input__inner {
        width: 300px;
    }

    #new-student .el-select>.el-input,
    #new-student .select-head>.el-input {
        width: 300px;
    }
</style>